package com.pet.platform.service.impl;

import com.pet.platform.dto.PetHealthDTO;
import com.pet.platform.entity.PetHealth;
import com.pet.platform.exception.BusinessException;
import com.pet.platform.mapper.PetHealthMapper;
import com.pet.platform.service.PetHealthService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PetHealthServiceImpl implements PetHealthService {

    @Resource
    private PetHealthMapper petHealthMapper;

    @Override
    public List<PetHealthDTO> findByPetId(Long petId) {
        List<PetHealth> records = petHealthMapper.findByPetId(petId);
        return records.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public PetHealthDTO findById(Long id) {
        PetHealth record = petHealthMapper.findById(id);
        if (record == null) {
            throw new BusinessException("健康记录不存在");
        }
        return convertToDTO(record);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(PetHealthDTO petHealthDTO) {
        PetHealth record = new PetHealth();
        BeanUtils.copyProperties(petHealthDTO, record);
        petHealthMapper.insert(record);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Long id, PetHealthDTO petHealthDTO) {
        PetHealth existingRecord = petHealthMapper.findById(id);
        if (existingRecord == null) {
            throw new BusinessException("健康记录不存在");
        }

        PetHealth record = new PetHealth();
        BeanUtils.copyProperties(petHealthDTO, record);
        record.setId(id);
        petHealthMapper.update(record);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        PetHealth existingRecord = petHealthMapper.findById(id);
        if (existingRecord == null) {
            throw new BusinessException("健康记录不存在");
        }
        petHealthMapper.delete(id);
    }

    private PetHealthDTO convertToDTO(PetHealth record) {
        if (record == null) {
            return null;
        }
        PetHealthDTO dto = new PetHealthDTO();
        BeanUtils.copyProperties(record, dto);
        if (record.getPet() != null) {
            dto.setPetName(record.getPet().getName());
        }
        return dto;
    }
}